<template>
  <div class="container">
    <xtx-select
      @change="changeYear"
      width="100px"
      v-model="year"
      :options="yearOptions"
      placeholder="年"
    ></xtx-select>
    <xtx-select
      @change="changeMonth"
      width="90px"
      v-model="month"
      :options="monthOptions"
      placeholder="月"
    ></xtx-select>
    <xtx-select
      width="90px"
      v-model="date"
      :options="dateOptions"
      placeholder="日"
      @change="changeDate"
    ></xtx-select>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'xtx-date',
  props: {
    value: {
      type: String,
      default: '',
      validate () {
        return /^\d{4}-\d{2}-\d{2}$/.test(this.value)
      }
    }
  },
  watch: {
    value: {
      handler () {
        if (this.value) {
          const arr = this.value.split('-')
          this.year = arr[0]
          this.month = arr[1]
          this.date = arr[2]
          this.initDateOptions()
        } else {
          this.year = ''
          this.month = ''
          this.date = ''
        }
      },
      immediate: true
    }
  },
  data () {
    return {
      year: '',
      yearOptions: [],
      month: '',
      monthOptions: [],
      date: '',
      dateOptions: []
    }
  },
  created () {
    this.initYearAndMonthOptions()
  },
  methods: {
    initYearAndMonthOptions () {
      const currYear = dayjs().year()
      for (let i = currYear; i >= 1949; i--) {
        this.yearOptions.push({ value: i.toString(), label: i + '年' })
      }
      for (let i = 1; i <= 12; i++) {
        this.monthOptions.push({ value: i > 10 ? i.toString() : '0' + i, label: i + '月' })
      }
    },
    initDateOptions () {
      this.dateOptions = []
      const dateCount = dayjs().year(this.year).month(this.month).date(0).date()
      for (let i = 1; i <= dateCount; i++) {
        this.dateOptions.push({ value: i > 10 ? i.toString() : '0' + i, label: i + '日' })
      }
    },
    changeYear () {
      this.month = ''
      this.date = ''
      this.dateOptions = []
    },
    changeMonth () {
      this.date = ''
      this.initDateOptions()
    },
    changeDate () {
      this.$emit('input', `${this.year}-${this.month}-${this.date}`)
    }
  }
}
</script>

<style scoped lang='less'>
.xtx-select ~ .xtx-select {
  margin-left: 10px;
}
</style>
